package com.travel.admin.exception;

import com.travel.admin.web.response.HandleResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 *@desc: controller的切面 异常统一捕获
 */
@ControllerAdvice
public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler({Exception.class, TravelException.class})
    @ResponseBody
    public HandleResp<String> Handle(HttpServletRequest request, Exception e) {
        logger.error("ExceptionHandle,e={}", e);
        String id = request.getHeader("id");
        if (e instanceof TravelException) {
            return HandleResp.failedResponse(((TravelException) e).getErrorCode(), id);
        } else if (e instanceof HttpMessageNotReadableException) {
            // 比如 @RequestBody 请求的body没有时会报此错误
            return HandleResp.failedResponse(TravelExceptionCode.PARAM_ERROR, id);
        } else if (e instanceof RuntimeException) {
            // 特别注意： 当该模块和调用它的模块存在分布式事务，则该模块抛出 RuntimeException
            logger.error("ExceptionHandle error:", e);
            throw new RuntimeException();
        }
        return HandleResp.failedResponse(TravelExceptionCode.SYSTEM_ERROR, id);
    }
}